package com.huadao.cart_ccs.common.scheudle;

import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduleUtil {
    private static final ScheduleUtil instance = new ScheduleUtil();
    private static ScheduledExecutorService executor;
//    private static List<ScheduledFuture> futureList;
    private long awaitTime = 1 * 1000;

    static {
        executor = Executors.newScheduledThreadPool(10);
//        futureList=new ArrayList<>();
    }

    public static ScheduleUtil getInstance() {
        return instance;
    }

    private ScheduleUtil() {

    }

    public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit){
        ScheduledFuture future=executor.scheduleAtFixedRate(command, initialDelay, period, unit);
//        futureList.add(future);
        return future;
    }

    public ScheduledFuture scheduleAtFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit){
        ScheduledFuture future=executor.scheduleWithFixedDelay(command, initialDelay, delay, unit);
//        futureList.add(future);
        return future;
    }

    public ScheduledFuture schedule(Runnable command,long delay, TimeUnit unit){
        ScheduledFuture future=executor.schedule(command, delay,unit);
//        futureList.add(future);
        return future;
    }

    public boolean cancel(Future future,boolean mayInterruptIfRunning){
        boolean canceled=future.cancel(mayInterruptIfRunning);
//        futureList.remove(future);
        return canceled;
    }

    public void terminal(){
        if(executor==null){
            return;
        }
        executor.shutdown();
        try {
            if(!executor.awaitTermination(awaitTime, TimeUnit.MILLISECONDS)){
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            executor.shutdownNow();
        }
    }
}
